const app = getApp();

Component({
  properties: {
    images: Array
  },

  data: {
    images: [],
    deleteIndex: null
  },

  methods: {
    addImage() {
      const that = this;
      let imgNum = that.data.images.length;
      wx.chooseImage({
        count: 6 - imgNum,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success(res) {
          let imgSrc = res.tempFilePaths; //图片的路径，数组
          let imgList = that.data.images;

          //检查图片大小，超过则选择失败
          if (!that.checkImageSize(res.tempFiles)) {
            wx.showToast({
              title:"图片大小不能超过4M，请重新选择"
            });
            return false;
          }

          wx.uploadFile({
            url: 'http://42.192.211.158:8888/zutassociation/common/upload', // 仅为示例，非真实的接口地址
            //url: 'http://localhost:8888/zutassociation/common/upload',
            filePath: imgSrc[0],
            name: 'file',
            headers: {Authorization: "Bearer " + wx.getStorageSync('Admin-Token')},
            // formData: {
            //   //和服务器约定的token, 一般也可以放在header中
            //   'session_token': wx.getStorageSync('session_token')
            // },
            success(res) {
              let data = JSON.parse(res.data)
              if (data.code !== 200) {
                this.setModal({content: '图片上传失败'})
                return;
              }
              let currentFile = {fileName: data.fileName, url: data.url};
              imgList.push(currentFile);
              that.setData({
                images: imgList
              });
              // that.fileList.push(currentFile)
            },
            fail: function (e) {
              console.log(e);
              this.setModal({content: '图片上传失败'})
            }
          });

          /*if (imgSrc.length === 1) {
            imgList.push(imgSrc[0]);
            that.setData({
              images: imgList
            });
          } else {
            imgList = imgList.concat(imgSrc);
            that.setData({
              images: imgList
            });
          }*/
          console.log(`当前已添加${that.data.images.length}张图片`);
          console.log(`${that.data.images}`);
        }
      });
    },

    previewImage(e) {
      let index = e.currentTarget.dataset.index;
      let imgList = this.data.images;
      wx.previewImage({
        current: imgList[index],
        urls: imgList
      });
    },

    deleteImage(e) {
      let index = e.currentTarget.dataset.index;
      let imgList = this.data.images;
      imgList.splice(index, 1);
      this.setData({
        images: imgList,
        deleteIndex: index
      });
      this.triggerEvent("delete", { index });
      console.log(`删除的下标为${index}的图片`);
    },

    checkImageSize(files) {
      let flag = files.every(ele => {
        if (ele.size > 400000) {
          return false;
        }
        return true;
      });
      if (flag) {
        return true;
      } else {
        return false;
      }
    }
  }
});
